using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ScintillaNET;

namespace TextKeep;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private string rootPath;
    private string list1Value;
    private string list2Value;
    private bool isSaved = true; // 默认为已保存


    private void Form1_Load(object sender, EventArgs e)
    {
        CenterToScreen();
        InitNumberMargin(scintilla1);
        toolStripStatusLabel1.Text = "";
        scintilla1.Text = "";

        // 设置选中文本的前景色（字体颜色）为白色
        scintilla1.SetSelectionForeColor(true, Color.White);
        // 设置选中文本的背景色为黑色
        scintilla1.SetSelectionBackColor(true, Color.Black);

        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        IConfigurationRoot configuration = configBuilder.Build();

        // 读取RootDirectory配置项，如果不存在，则使用默认路径
        string rootDirectory = configuration.GetValue<string>("RootDirectory") ?? Path.Combine(Directory.GetCurrentDirectory(), "DefaultFolder");
        rootPath = rootDirectory;


        // 创建一个新的字典用于设置新的配置项
        var newSettings = new Dictionary<string, string>
        {
            { "RootDirectory", rootPath }
        };

        // 使用 AddInMemoryCollection 方法添加新的配置项
        configBuilder.AddInMemoryCollection(newSettings);

        // 重新构建 IConfigurationRoot 对象
        configuration = configBuilder.Build();

        // 将新配置保存到文件中
        File.WriteAllText("appsettings.json", JsonConvert.SerializeObject(configuration.AsEnumerable().ToDictionary(x => x.Key, x => x.Value)));

        LoadDirectories(rootPath);

        toolStripStatusLabel1.Text = rootPath;
        // 其他配置项的读取方式类似，根据你的需求读取配置信息
    }

    //新建文件夹
    private void button1_Click(object sender, EventArgs e)
    {
        // 检查根路径是否存在，如果不存在则创建
        if (!Directory.Exists(rootPath))
        {
            Directory.CreateDirectory(rootPath);
            Console.WriteLine($"Root directory '{rootPath}' created.");
        }


        string folderName = FileUtil.GetNextFolderName(rootPath, "新建文件夹-"); // 替换为你想要创建的文件夹名字
        string folderPath = Path.Combine(rootPath, folderName);
        // 检查文件夹是否存在，如果不存在则创建
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
            Console.WriteLine($"Folder '{folderPath}' created in root directory.");
        }

        FileItem item = new FileItem { FileName = folderName, IsModified = false };
        listBox1.Items.Add(item);
    }

    //新建文件
    private void button2_Click(object sender, EventArgs e)
    {
        //string filePath = @"C:\path\to\your\file.txt"; // 替换为你想要创建文件的路径
        string fileName = FileUtil.GetNextFileName(Path.Combine(rootPath, list1Value), "未命名-");
        string filePath = Path.Combine(rootPath, list1Value, fileName);

        try
        {
            // 创建文本文件并写入内容
            using (StreamWriter writer = File.CreateText(filePath))
            {
                //writer.WriteLine("Hello, this is a new text file!");
                // 在此可以继续写入其他内容...
            }

            Console.WriteLine($"File created successfully at: {filePath}");

            FileItem item = new FileItem { FileName = fileName, IsModified = false };
            listBox2.Items.Add(item);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }

    private void LoadDirectories(string rootPath)
    {
        //string rootPath = "YourRootPath"; // 替换为你的根路径

        // 检查根路径是否存在
        if (Directory.Exists(rootPath))
        {
            string[] directories = Directory.GetDirectories(rootPath);

            // 将获取到的目录添加到 ListBox 控件中
            foreach (string directory in directories)
            {
                string directoryName = Path.GetFileName(directory);
                listBox1.Items.Add(directoryName);
            }
        }
        else
        {
            //MessageBox.Show("Root path does not exist!");
        }
    }

    private void LoadFilesToListBox(string folderPath)
    {
        listBox2.Items.Clear(); // 清空现有列表项
        try
        {
            if (Directory.Exists(folderPath))
            {
                string[] files = Directory.GetFiles(folderPath);

                foreach (string file in files)
                {
                    string fileName = Path.GetFileName(file);
                    // 添加项到 ListBox
                    FileItem item = new FileItem { FileName = fileName, IsModified = false };
                    listBox2.Items.Add(item);
                }
            }
            else
            {
                MessageBox.Show("Folder path does not exist!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"An error occurred: {ex.Message}");
        }
    }

    //
    //初始化显示行号
    //
    private void InitNumberMargin(Scintilla scintilla1)
    {
        int NUMBER_MARGIN = 0;
        var nums = scintilla1.Margins[NUMBER_MARGIN];
        nums.Width = 32;
        nums.Type = MarginType.Number;
        nums.Sensitive = true;
        nums.Mask = 0;
    }


    //更新行号宽度
    private void updateLineNumberWidth()
    {
        int lines = scintilla1.Lines.Count;
        int digits = lines == 0 ? 1 : (int)Math.Floor(Math.Log10(lines) + 1);
        int marginWidth = (int)(scintilla1.TextWidth(Style.LineNumber, new string('9', digits)) + 6); // 加上一些额外空间

        scintilla1.Margins[0].Width = marginWidth + 20;
    }

    //文本内容修改
    private void scintilla1_TextChanged(object sender, EventArgs e)
    {
        updateLineNumberWidth();
        if (!isSaved) return;
        isSaved = false;

        SetSelectedItemColor(Color.Red); // 设置选中项颜色为红色

        // 获取选中项的索引
        int selectedIndex = listBox2.SelectedIndex;

        if (selectedIndex != -1) // 检查是否有选中的项
        {
            // 使用类型转换获取选中的 FileItem 对象
            FileItem selectedItem = (FileItem)listBox2.Items[selectedIndex];

            // 现在你可以使用 selectedItem 来操作选中的 FileItem 对象
            selectedItem.IsModified = true;
            listBox2.Items[selectedIndex] = selectedItem;
        }
    }

    //切换目录
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
            string selectedValue = listBox1.SelectedItem.ToString();
            if (list1Value == selectedValue) return;

            list1Value = selectedValue;
            list2Value = "";

            // 处理选中的值
            Console.WriteLine($"Selected item: {selectedValue}");

            LoadFilesToListBox(Path.Combine(rootPath, selectedValue));
            CleanTextArea();
        }
    }

    //切换文件
    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        Console.WriteLine("listBox2_SelectedIndexChanged");
        // 循环遍历listBox2中的所有项
        // for (int i = 0; i < listBox2.Items.Count; i++)
        // {
        //     if (listBox2.Items[i] is FileItem fileItem) // 检查是否是 FileItem 类型
        //     {
        //         if (fileItem.IsModified) // 如果IsModified为true，则修改为false
        //         {
        //             fileItem.IsModified = false;
        //             // 重新设置修改后的项回到listBox2中
        //             listBox2.Items[i] = fileItem;
        //         }
        //     }
        // }
        //
        if (listBox2.SelectedIndex != -1)
        {
            FileItem selectedItem = (FileItem)listBox2.SelectedItem;
            //string selectedValue = listBox2.SelectedItem.ToString();
            string selectedValue = selectedItem.FileName;
            if (list2Value == selectedValue) return;

            list2Value = selectedValue;

            // 处理选中的值
            Console.WriteLine($"Selected item: {selectedValue}");

            string textFile = FileUtil.ReadTextFile(Path.Combine(rootPath, list1Value, selectedValue));
            isSaved = false;
            scintilla1.Text = textFile;
            scintilla1.Enabled = true;
            isSaved = true;
        }
    }

    private void CleanTextArea()
    {
        scintilla1.Text = "";
        scintilla1.Enabled = false;
    }


    private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Console.WriteLine("保存ToolStripMenuItem_Click");

        FileUtil.WriteTextFile(Path.Combine(rootPath, list1Value, list2Value), scintilla1.Text);

        RestoreSelectedItemColor(); // 还原颜色
        isSaved = true; // 设置为已保存状态

        // 获取选中项的索引
        int selectedIndex = listBox2.SelectedIndex;

        if (selectedIndex != -1) // 检查是否有选中的项
        {
            // 使用类型转换获取选中的 FileItem 对象
            FileItem selectedItem = (FileItem)listBox2.Items[selectedIndex];

            // 现在你可以使用 selectedItem 来操作选中的 FileItem 对象
            selectedItem.IsModified = false;
            listBox2.Items[selectedIndex] = selectedItem;
        }
    }

    // 设置选中项颜色为指定颜色
    private void SetSelectedItemColor(Color color)
    {
        if (listBox2.SelectedIndex != -1)
        {
            // listBox2.SelectionMode = SelectionMode.None;
            // listBox2.SelectionMode = SelectionMode.One;
            // listBox2.SelectedItem = listBox2.SelectedItem;
            // listBox2.BackColor = color;
        }
    }

    // 还原选中项颜色为默认颜色
    private void RestoreSelectedItemColor()
    {
        //SetSelectedItemColor(SystemColors.Window); // 还原默认颜色
    }

    //删除目录
    private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string folderPath = Path.Combine(rootPath, list1Value);
        Console.WriteLine($"删除目录{folderPath}");
        FileUtility.DeleteFolder(folderPath);
        // 获取选中项的索引
        int selectedIndex = listBox1.SelectedIndex;
        // 假设listBox2是你的ListBox控件
        if (selectedIndex != -1) // 检查是否有选中的项
        {
            listBox1.Items.RemoveAt(selectedIndex); // 根据选中项的索引移除该项
            CleanTextArea();
            listBox2.Items.Clear();
        }
    }

    //显示目录
    private void 在Explorer中显示ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string folderPath = Path.Combine(rootPath, list1Value);
        Console.WriteLine($"显示目录{folderPath}");
        FileUtility.OpenFolderInExplorer(folderPath);
    }

    //删除文件
    private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        string filePath = Path.Combine(rootPath, list1Value, list2Value);
        Console.WriteLine($"删除文件{filePath}");
        FileUtility.DeleteFile(filePath);

        // 获取选中项的索引
        int selectedIndex = listBox2.SelectedIndex;
        // 假设listBox2是你的ListBox控件
        if (selectedIndex != -1) // 检查是否有选中的项
        {
            listBox2.Items.RemoveAt(selectedIndex); // 根据选中项的索引移除该项
            CleanTextArea();
        }
    }

    //显示文件
    private void 在Explorer中显示ToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        string filePath = Path.Combine(rootPath, list1Value, list2Value);
        Console.WriteLine($"显示文件{filePath}");
        FileUtility.OpenFileInExplorer(filePath);
    }
}